package com.itheima.reggie.service.impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author: qingtao
 * @Date 2022/3/22 20:04
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;
    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //1. 根据用户的id与dish_id 或者setmeal_id查看购物车表是否存在该购物项
        ShoppingCart cart = shoppingCartMapper.findUidAndDisOrSid(shoppingCart);
        if (cart == null){
            //2. 如果查询是空，新插入一条记录
            //补全数据
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(shoppingCart);
            cart = shoppingCart;
        }else {
            //3. 如果不为空，数量+1
            cart.setNumber(cart.getNumber()+1);
            shoppingCartMapper.update(cart);
        }
        return cart;
    }

    /**
     * 减少
     *
     * @param shoppingCart
     * @return
     */
    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        ShoppingCart cart = shoppingCartMapper.findUidAndDisOrSid(shoppingCart);
        cart.setNumber(cart.getNumber()-1);
        shoppingCartMapper.update(cart);
        return cart;
    }

    /**
     * 根据userID查找菜品
     *
     * @param userId
     * @return
     */
    @Override
    public List<ShoppingCart> findCartByUserId(Long userId) {
        return shoppingCartMapper.findCartByUserId(userId);
    }

    /**
     * 清空购物车
     * 根据userId
     * @param userId
     * @return
     */
    @Override
    public boolean clear(Long userId) {
        return shoppingCartMapper.clear(userId)>0;
    }
}
